package com.xiaoliu.tools;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
// 

import com.xiaoliu.pojo.DataBaseConfig;
 
/**
 * 连接DB工具
 *
 */
@Component
public class DBUtil {
	protected final  Logger log= (Logger) LoggerFactory.getLogger(DBUtil.class);
	
	//获取配置
	@Autowired
	private  DataBaseConfig config;	
	
	public  Connection conn = null;

	public String url ;

	/**
	 * 获得连接
	 * @return
	 */
	public  Connection getConnection() {
		try {
			// 注册驱动,为了兼容JVM所以才加上newInstance()
			Class.forName(config.getDriver()).newInstance();
			try {
				url = config.getUrl();
//				System.out.println(config.getUrl());
				//管理连接
				conn = DriverManager.getConnection(url, config.getUsername(), config.getPassword());
			} catch (SQLException e) {
				log.error("connection:{}","An exception connecting to the database");
				e.printStackTrace();
			}
		} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
			log.error("class.forName:{}","DRIVER ERROR,please check application.properites ");
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * 关闭数据库连接
	 */
	public  void closeConnection() {
		if(null!=conn) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				log.error("close connect:{}","Close data exception");
			}
		}
	}	
	
}